package com.jingwu.example.graphql;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coxautodev.graphql.tools.GraphQLQueryResolver;
import com.jingwu.example.pojo.entity.BookDO;
import com.jingwu.example.pojo.query.BookQuery;
import com.jingwu.example.pojo.vo.BookVO;
import com.jingwu.example.pojo.vo.Pagination;
import com.jingwu.example.repo.BookRepository;
import org.springframework.stereotype.Service;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.util.List;
import java.util.Objects;

import static com.deepexi.web.support.pojo.converter.utils.ConverterUtils.convert;
import static com.deepexi.web.support.pojo.converter.utils.ConverterUtils.convertAll;

/**
 * @author jingwu
 * @since 2021/2/1
 */
@Service
public class BookQueryResolver implements GraphQLQueryResolver {

    private final BookRepository repository;

    public BookQueryResolver(BookRepository repository) {
        this.repository = repository;
    }

    public List<BookVO> listBooks(BookQuery query) {
        List<BookDO> list = repository.select(query);
        return convertAll(list, BookVO.class);
    }

    public Pagination<BookVO> getBookPage(BookQuery query) {
        Page<BookDO> page = repository.selectPage(query);
        return new Pagination<>(page.getTotal(), convertAll(page.getRecords(), BookVO.class));
    }

    public BookVO getBook(Integer id) {
        BookDO entity = repository.selectById(id);
        if (Objects.isNull(entity)) {
            return null;
        }
        return convert(entity, BookVO.class);
    }

}
